#pragma once

#include<iostream>
#include<pthread.h>
#include<queue>
#include<ctime>
#include<cstdlib>
#define NUM 5
using namespace std;

template<class T>
class ThreadPool
{
  public:
  ThreadPool(int cap=NUM):thread_num(cap)
  {
    pthread_mutex_init(&_lock,nullptr);
    pthread_cond_init(&_cond,nullptr);
  }
  void LockQueue()
  {
    pthread_mutex_lock(&_lock);
  }
  void UnlockQueue()
  {
    pthread_mutex_unlock(&_lock);
  }
  void Wait()
  {
    pthread_cond_wait(&_cond,&_lock);
  }
  void Wake()
  {
    pthread_cond_signal(&_cond);
  }
  bool isQueueEmpty()
  {
    return _task_queue.size()==0?true:false;
  }
  //为什么定义成静态成员：为了不让外部调用这个函数，避免了this指针的调用问题
  static void*Rountine(void *arg)
  {
    pthread_detach(pthread_self());
    ThreadPool*self=(ThreadPool*)arg;
    //然后判断队列是否为空，循环等待，避免被意外唤醒
    while(true)
    {
      self->LockQueue();
      if(self->isQueueEmpty())
      {
       self-> Wait();
      }
      //任务队列有任务
      T t;
      self->Pop(t);
      self->UnlockQueue();
      t.run();   
  }
}
  void Thread_pool_init()
  {
    pthread_t tid;
    for(int i=0;i<thread_num;i++)
    {
      pthread_create(&tid,nullptr,Rountine,this);
    }
  }
  void push(const T& in)
  {
    LockQueue();
    _task_queue.push(in);
    UnlockQueue();
    Wake();
  }
  void Pop ( T &out)
  {
    out=_task_queue.front();
    _task_queue.pop();
  }
  ~ThreadPool()
  {
    pthread_mutex_destroy(&_lock);
    pthread_cond_destroy(&_cond);
  }
  private:
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
    queue<T>_task_queue;
    int thread_num;


};
